<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ESP32-S3 WiFi配置</title>
    <style>
        * {
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            margin: 0;
            padding: 20px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
        }

        h1 {
            color: #2c3e50;
            text-align: center;
            margin-bottom: 30px;
            font-weight: 600;
        }

        .container {
            max-width: 500px;
            margin: 0 auto;
            background-color: white;
            padding: 30px;
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
            backdrop-filter: blur(10px);
        }

        @media (max-width: 600px) {
            .container {
                margin: 0 10px;
            padding: 20px;
            }
            body {
                padding: 10px;
            }
        }

        .wifi-list {
            margin: 20px 0;
            max-height: 400px;
            overflow-y: auto;
            border-radius: 8px;
            border: 1px solid #e0e0e0;
        }

        .wifi-item {
            padding: 15px;
            border-bottom: 1px solid #f0f0f0;
            cursor: pointer;
            display: flex;
            justify-content: space-between;
            align-items: center;
            transition: all 0.3s ease;
            position: relative;
        }

        .wifi-item:last-child {
            border-bottom: none;
        }

        .wifi-item:hover {
            background-color: #f8f9ff;
            transform: translateX(5px);
        }

        .wifi-item.selected {
            background: linear-gradient(135deg, #3498db, #2980b9);
            color: white;
            transform: translateX(5px);
        }

        .wifi-item.selected::before {
            content: '✓';
            position: absolute;
            left: -10px;
            background: #27ae60;
            color: white;
            border-radius: 50%;
            width: 20px;
            height: 20px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 12px;
            font-weight: bold;
        }

        .wifi-name {
            font-weight: 600;
            font-size: 16px;
            margin-bottom: 2px;
        }

        .wifi-signal {
            font-size: 12px;
            color: #666;
            display: flex;
            align-items: center;
            gap: 5px;
        }

        .wifi-item.selected .wifi-signal {
            color: #ecf0f1;
        }

        .signal-icon {
            width: 16px;
            height: 16px;
            display: inline-block;
            position: relative;
        }

        .signal-bars {
            display: flex;
            align-items: end;
            gap: 1px;
            height: 12px;
        }

        .signal-bar {
            width: 2px;
            background-color: #ccc;
            border-radius: 1px;
        }

        .signal-bar.active {
            background-color: #27ae60;
        }

        .wifi-item.selected .signal-bar.active {
            background-color: #fff;
        }

        .signal-bar:nth-child(1) { height: 3px; }
        .signal-bar:nth-child(2) { height: 6px; }
        .signal-bar:nth-child(3) { height: 9px; }
        .signal-bar:nth-child(4) { height: 12px; }

        .form-group {
            margin: 15px 0;
        }

        label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }

        .input-group {
            position: relative;
            margin-bottom: 20px;
        }

        input[type="text"],
        input[type="password"] {
            width: 100%;
            padding: 12px 16px;
            border: 2px solid #e0e0e0;
            border-radius: 8px;
            font-size: 16px;
            transition: all 0.3s ease;
            background-color: #fafafa;
        }

        input[type="text"]:focus,
        input[type="password"]:focus {
            outline: none;
            border-color: #3498db;
            background-color: white;
            box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.1);
        }

        .password-toggle {
            position: absolute;
            right: 12px;
            top: 50%;
            transform: translateY(-50%);
            background: none;
            border: none;
            cursor: pointer;
            color: #666;
            width: auto;
            margin: 0;
            padding: 4px;
            font-size: 14px;
        }

        .password-toggle:hover {
            color: #3498db;
            transform: translateY(-50%) scale(1.1);
            box-shadow: none;
        }

        button {
            background: linear-gradient(135deg, #3498db, #2980b9);
            color: white;
            padding: 12px 24px;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            width: 100%;
            margin: 10px 0;
            font-size: 16px;
            font-weight: 500;
            transition: all 0.3s ease;
            position: relative;
            overflow: hidden;
        }

        button::before {
            content: '';
            position: absolute;
            top: 0;
            left: -100%;
            width: 100%;
            height: 100%;
            background: linear-gradient(90deg, transparent, rgba(255,255,255,0.2), transparent);
            transition: left 0.5s;
        }

        button:hover::before {
            left: 100%;
        }

        button:hover {
            background: linear-gradient(135deg, #2980b9, #1f618d);
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(52, 152, 219, 0.3);
        }

        button:active {
            transform: translateY(0);
        }

        button:disabled {
            background: #bdc3c7;
            cursor: not-allowed;
            transform: none;
            box-shadow: none;
        }

        button:disabled::before {
            display: none;
        }

        .status {
            padding: 10px;
            margin: 10px 0;
            border-radius: 4px;
            text-align: center;
        }

        .status.success {
            background-color: #d4edda;
            border: 1px solid #c3e6cb;
            color: #155724;
        }

        .status.error {
            background-color: #f8d7da;
            border: 1px solid #f5c6cb;
            color: #721c24;
        }

        .status.info {
            background-color: #d1ecf1;
            border: 1px solid #b8daff;
            color: #0c5460;
        }

        .security {
            font-size: 11px;
            color: #666;
            display: inline-flex;
            align-items: center;
            gap: 3px;
        }

        .security-icon {
            width: 12px;
            height: 12px;
        }

        .loading {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 2px solid #f3f3f3;
            border-top: 2px solid #3498db;
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin-right: 8px;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        .progress-bar {
            width: 100%;
            height: 4px;
            background-color: #e0e0e0;
            border-radius: 2px;
            overflow: hidden;
            margin: 10px 0;
        }

        .progress-fill {
            height: 100%;
            background: linear-gradient(90deg, #3498db, #2980b9);
            border-radius: 2px;
            transition: width 0.3s ease;
            width: 0%;
        }

        .toast {
            position: fixed;
            top: 20px;
            right: 20px;
            background: white;
            padding: 16px 20px;
            border-radius: 8px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
            border-left: 4px solid #3498db;
            z-index: 1000;
            transform: translateX(100%);
            transition: transform 0.3s ease;
        }

        .toast.show {
            transform: translateX(0);
        }

        .toast.success {
            border-left-color: #27ae60;
        }

        .toast.error {
            border-left-color: #e74c3c;
        }

        .refresh-btn {
            background: linear-gradient(135deg, #28a745, #20c997);
            width: calc(50% - 5px);
            display: inline-block;
        }

        .refresh-btn:hover {
            background: linear-gradient(135deg, #218838, #17a085);
        }

        .button-group {
            display: flex;
            gap: 10px;
            margin-bottom: 20px;
        }

        .clear-btn {
            background: linear-gradient(135deg, #e74c3c, #c0392b);
            width: calc(50% - 5px);
            display: inline-block;
        }

        .clear-btn:hover {
            background: linear-gradient(135deg, #c0392b, #a93226);
        }

        /* 错误处理相关样式 */
        .error-actions {
            display: flex;
            flex-wrap: wrap;
            gap: 8px;
            align-items: center;
            margin-top: 15px;
        }

        .error-action {
            flex: none;
            width: auto !important;
            padding: 8px 16px !important;
            margin: 4px 0 !important;
            font-size: 14px !important;
            min-width: auto;
        }

        .error-action:hover {
            transform: translateY(-1px);
        }

        .password-error {
            border-color: #e74c3c !important;
            background-color: #fdf2f2 !important;
            animation: shake 0.5s ease-in-out;
        }

        @keyframes shake {
            0%, 100% { transform: translateX(0); }
            25% { transform: translateX(-5px); }
            75% { transform: translateX(5px); }
        }

        .error-suggestion {
            background-color: #fff3cd;
            border: 1px solid #ffeaa7;
            color: #6c5700;
            padding: 12px;
            border-radius: 6px;
            margin-top: 10px;
            font-size: 13px;
            line-height: 1.4;
        }

        .error-suggestion::before {
            content: '💡 ';
            font-weight: bold;
        }

        /* IP地址显示样式 */
        .ip-info {
            background: linear-gradient(135deg, #e8f5e8, #f0f8ff);
            border: 2px solid #27ae60;
            border-radius: 8px;
            padding: 15px;
            margin: 15px 0;
            text-align: center;
            box-shadow: 0 2px 10px rgba(39, 174, 96, 0.2);
        }

        .ip-info strong {
            color: #27ae60;
            font-size: 18px;
        }

        .ip-info small {
            color: #666;
            display: block;
            margin-top: 5px;
        }

        /* 密码错误时的特殊效果 */
        .password-input-error {
            position: relative;
        }

        .password-input-error::after {
            content: '❌';
            position: absolute;
            right: 45px;
            top: 50%;
            transform: translateY(-50%);
            color: #e74c3c;
            pointer-events: none;
        }
    </style>
</head>

<body>
    <div class="container">
        <h1>ESP32-S3 WiFi配置</h1>
        <div class="button-group">
            <button class="refresh-btn" onclick="scanWiFi()" id="scan-btn">
                <span id="scan-text">刷新WiFi列表</span>
            </button>
            <button class="clear-btn" onclick="clearConfig()">清除WiFi配置</button>
        </div>
        <div id="wifi-list" class="wifi-list">
            <div class="loading"></div>
            正在扫描WiFi网络...
        </div>
        <form id="wifi-form">
            <div class="form-group">
                <label for="ssid">WiFi名称 (SSID):</label>
                <div class="input-group">
                    <input type="text" id="ssid" name="ssid" required placeholder="选择或手动输入WiFi名称">
                </div>
            </div>
            <div class="form-group">
                <label for="password">WiFi密码:</label>
                <div class="input-group">
                    <input type="password" id="password" name="password" placeholder="输入WiFi密码">
                    <button type="button" class="password-toggle" onclick="togglePassword()" id="password-toggle">👁️</button>
                </div>
            </div>
            <div id="progress-container" style="display: none;">
                <div class="progress-bar">
                    <div class="progress-fill" id="progress-fill"></div>
                </div>
                <div id="progress-text" style="text-align: center; font-size: 14px; color: #666; margin-top: 5px;"></div>
            </div>
            <button type="submit" id="connect-btn">
                <span id="connect-text">连接WiFi</span>
            </button>
        </form>
        <div id="status" class="status" style="display: none;"></div>
    </div>

    <script>
        let selectedSSID = '';
        let isScanning = false;
        let isConnecting = false;
        let retryCount = 0;
        const MAX_RETRY = 3;

        // 密码显示/隐藏切换
        function togglePassword() {
            const passwordInput = document.getElementById('password');
            const toggleBtn = document.getElementById('password-toggle');
            
            if (passwordInput.type === 'password') {
                passwordInput.type = 'text';
                toggleBtn.textContent = '🙈';
            } else {
                passwordInput.type = 'password';
                toggleBtn.textContent = '👁️';
            }
        }

        // 显示Toast通知
        function showToast(message, type = 'info') {
            // 移除现有的toast
            const existingToast = document.querySelector('.toast');
            if (existingToast) {
                existingToast.remove();
            }

            const toast = document.createElement('div');
            toast.className = `toast ${type}`;
            toast.textContent = message;
            document.body.appendChild(toast);

            // 触发显示动画
            setTimeout(() => toast.classList.add('show'), 100);

            // 3秒后自动移除
            setTimeout(() => {
                toast.classList.remove('show');
                setTimeout(() => toast.remove(), 300);
            }, 3000);
        }

        // 更新进度条
        function updateProgress(percent, text = '') {
            const progressContainer = document.getElementById('progress-container');
            const progressFill = document.getElementById('progress-fill');
            const progressText = document.getElementById('progress-text');
            
            progressContainer.style.display = 'block';
            progressFill.style.width = percent + '%';
            progressText.textContent = text;
            
            if (percent >= 100) {
                setTimeout(() => {
                    progressContainer.style.display = 'none';
                }, 1000);
            }
        }

        function scanWiFi() {
            if (isScanning) return;
            
            isScanning = true;
            const scanBtn = document.getElementById('scan-btn');
            const scanText = document.getElementById('scan-text');
            
            scanBtn.disabled = true;
            scanText.innerHTML = '<div class="loading"></div>扫描中...';
            
            document.getElementById('wifi-list').innerHTML = '<div class="loading"></div>正在扫描WiFi网络...';
            
            fetch('/scan')
                .then(response => {
                    if (!response.ok) throw new Error('网络请求失败');
                    return response.json();
                })
                .then(data => {
                    displayWiFiList(data.networks);
                    showToast(`发现 ${data.networks.length} 个WiFi网络`, 'success');
                })
                .catch(error => {
                    document.getElementById('wifi-list').innerHTML = 
                        '<div style="text-align: center; color: #e74c3c; padding: 20px;">' +
                        '<p>❌ 扫描失败</p>' +
                        '<p style="font-size: 12px;">错误: ' + error.message + '</p>' +
                        '<button onclick="scanWiFi()" style="margin-top: 10px;">重新扫描</button>' +
                        '</div>';
                    showToast('扫描失败: ' + error.message, 'error');
                })
                .finally(() => {
                    isScanning = false;
                    scanBtn.disabled = false;
                    scanText.textContent = '刷新WiFi列表';
                });
        }

        // 创建信号强度图标
        function createSignalIcon(rssi) {
            const strength = getSignalStrength(rssi);
            const icon = document.createElement('div');
            icon.className = 'signal-icon';
            
            const bars = document.createElement('div');
            bars.className = 'signal-bars';
            
            for (let i = 1; i <= 4; i++) {
                const bar = document.createElement('div');
                bar.className = `signal-bar ${i <= strength ? 'active' : ''}`;
                bars.appendChild(bar);
            }
            
            icon.appendChild(bars);
            return icon;
        }

        // 获取信号强度等级（1-4）
        function getSignalStrength(rssi) {
            if (rssi > -50) return 4;
            if (rssi > -60) return 3;
            if (rssi > -70) return 2;
            if (rssi > -80) return 1;
            return 1;
        }

        // 获取安全性图标
        function getSecurityIcon(authmode) {
            return authmode === 0 ? '🔓' : '🔒';
        }

        function displayWiFiList(networks) {
            const wifiList = document.getElementById('wifi-list');
            if (networks.length === 0) {
                wifiList.innerHTML = '<div style="text-align: center; color: #666; padding: 40px;">📶<br/>未找到WiFi网络<br/><small>请检查WiFi是否开启或尝试刷新</small></div>';
                return;
            }

            // 按信号强度排序
            networks.sort((a, b) => b.rssi - a.rssi);
            
            wifiList.innerHTML = '';
            networks.forEach((network, index) => {
                const wifiItem = document.createElement('div');
                wifiItem.className = 'wifi-item';
                wifiItem.onclick = () => selectWiFi(network.ssid, wifiItem);
                wifiItem.style.animationDelay = (index * 0.1) + 's';
                
                const signalIcon = createSignalIcon(network.rssi);
                const securityIcon = getSecurityIcon(network.authmode);
                
                wifiItem.innerHTML = `
            <div>
                        <div class="wifi-name">${network.ssid || '(隐藏网络)'}</div>
                        <div class="security">
                            ${securityIcon} ${getSecurityText(network.authmode)}
                        </div>
                    </div>
                    <div class="wifi-signal">
                        ${signalIcon.outerHTML}
                        ${getSignalText(network.rssi)}
            </div>
        `;
                wifiList.appendChild(wifiItem);
            });
        }

        function selectWiFi(ssid, element) {
            document.querySelectorAll('.wifi-item').forEach(item => item.classList.remove('selected'));
            element.classList.add('selected');
            document.getElementById('ssid').value = ssid;
            selectedSSID = ssid;
            
            // 聚焦到密码输入框
            const passwordInput = document.getElementById('password');
            passwordInput.focus();
            
            console.log('选中WiFi:', ssid);
            showToast('已选择WiFi: ' + ssid, 'info');
            
            // 添加选中动画效果
            element.style.transform = 'scale(1.02)';
            setTimeout(() => {
                element.style.transform = '';
            }, 200);
        }

        function getSecurityText(authmode) {
            const modes = { 0: '开放', 1: 'WEP', 2: 'WPA_PSK', 3: 'WPA2_PSK', 4: 'WPA_WPA2_PSK', 5: 'WPA2_ENTERPRISE' };
            return modes[authmode] || '未知';
        }

        function getSignalText(rssi) {
            if (rssi > -50) return '极强';
            if (rssi > -60) return '强';
            if (rssi > -70) return '中';
            if (rssi > -80) return '弱';
            return '极弱';
        }

        document.getElementById('wifi-form').addEventListener('submit', function (e) {
            e.preventDefault();
            
            if (!validateForm()) {
                return;
            }
            
            const ssid = document.getElementById('ssid').value.trim();
            const password = document.getElementById('password').value;
            
            connectWiFi(ssid, password);
        });

        // 页面加载完成后的初始化
        window.onload = function () {
            // 自动扫描WiFi
            scanWiFi();
            
            // 显示使用提示
            showToast('🔧 快捷键提示：Ctrl+R 刷新列表，Esc 清除选择', 'info');
            
            // 为输入框添加实时验证
            const ssidInput = document.getElementById('ssid');
            const passwordInput = document.getElementById('password');
            
            ssidInput.addEventListener('input', function() {
                if (this.value.length > 32) {
                    this.style.borderColor = '#e74c3c';
                    showToast('WiFi名称过长', 'error');
                } else {
                    this.style.borderColor = '#e0e0e0';
                }
            });
            
            passwordInput.addEventListener('input', function() {
                if (this.value.length > 64) {
                    this.style.borderColor = '#e74c3c';
                    showToast('WiFi密码过长', 'error');
                } else {
                    this.style.borderColor = '#e0e0e0';
                }
            });
        };

        function connectWiFi(ssid, password) {
            if (isConnecting) return;
            
            isConnecting = true;
            const connectBtn = document.getElementById('connect-btn');
            const connectText = document.getElementById('connect-text');
            
            connectBtn.disabled = true;
            connectText.innerHTML = '<div class="loading"></div>连接中...';
            
            // 显示连接进度
            updateProgress(10, '准备连接...');
            showStatus('正在连接WiFi网络...', 'info');
            
            console.log('连接WiFi:', ssid);
            
            // 模拟连接进度
            setTimeout(() => updateProgress(30, '验证凭据...'), 500);
            setTimeout(() => updateProgress(60, '建立连接...'), 1500);
            setTimeout(() => updateProgress(80, '获取IP地址...'), 2500);
            
            fetch('/connect', {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: `ssid=${encodeURIComponent(ssid)}&password=${encodeURIComponent(password)}`
            })
                .then(response => {
                    if (!response.ok) throw new Error('网络请求失败');
                    return response.json();
                })
                .then(data => {
                    if (data.success) {
                        updateProgress(100, '连接成功！');
                        
                        // 显示IP地址信息
                        const ipInfo = data.ip ? `，设备IP: ${data.ip}` : '';
                        showStatus(`WiFi连接成功${ipInfo}！设备将在5秒后重启...`, 'success');
                        showToast(`WiFi连接成功！${ipInfo ? `设备IP: ${data.ip}` : '设备即将重启'}`, 'success');
                        
                        // 显示倒计时和IP信息
                        let countdown = 5;
                        const countdownInterval = setInterval(() => {
                            countdown--;
                            if (countdown > 0) {
                                showStatus(`WiFi连接成功${ipInfo}！设备将在${countdown}秒后重启...`, 'success');
                            } else {
                                showStatus('设备正在重启，配网完成！', 'success');
                                clearInterval(countdownInterval);
                                
                                // 显示最终提示，包含IP信息
                                setTimeout(() => {
                                    const finalMessage = data.ip ? 
                                        `配网完成！设备已重启，IP地址: ${data.ip}，您可以关闭此页面` : 
                                        '配网完成！设备已重启，您可以关闭此页面';
                                    showStatus(finalMessage, 'success');
                                }, 2000);
                            }
                        }, 1000);
                        
                        retryCount = 0;
                        
                        // 禁用所有输入和按钮
                        document.getElementById('ssid').disabled = true;
                        document.getElementById('password').disabled = true;
                        document.getElementById('connect-btn').disabled = true;
                        document.getElementById('scan-btn').disabled = true;
                        
                        // 如果有IP地址，显示访问链接提示
                        if (data.ip) {
                            setTimeout(() => {
                                const accessInfo = document.createElement('div');
                                accessInfo.className = 'ip-info';
                                accessInfo.innerHTML = `
                                    🌐 <strong>设备访问信息</strong><br/>
                                    设备IP地址: <strong>${data.ip}</strong><br/>
                                    <small>重启后可通过 <strong>http://${data.ip}</strong> 访问设备摄像头</small>
                                `;
                                document.getElementById('status').appendChild(accessInfo);
                            }, 6000);
                        }
                        
                    } else {
                        throw new Error(data.message || '连接失败');
                    }
                })
                .catch(error => {
                    console.error('连接错误:', error);
                    
                    // 分析错误类型和原因
                    const errorInfo = analyzeWiFiError(error.message);
                    
                    // 根据错误类型决定是否重试
                    const shouldRetry = errorInfo.canRetry && retryCount < MAX_RETRY;
                    if (shouldRetry) {
                        retryCount++;
                    }
                    
                    let errorMessage = errorInfo.message;
                    if (shouldRetry) {
                        errorMessage += ` (${retryCount}/${MAX_RETRY}次重试)`;
                        showRetryOption(ssid, password, errorInfo, shouldRetry);
                    } else {
                        // 对于密码错误等不应该重试的错误，提供修改建议
                        showErrorActions(errorInfo);
                    }
                    
                    showStatus(errorMessage, 'error');
                    showToast(errorInfo.shortMessage, 'error');
                    
                    // 密码错误时的特殊处理
                    if (errorInfo.type === 'password') {
                        setTimeout(() => {
                            handlePasswordError();
                        }, 500);
                        
                        // 显示明确的密码错误提示
                        showToast('密码错误！热点仍开启，请重新输入正确密码', 'error');
                    }
                    
                    // 隐藏进度条
                    document.getElementById('progress-container').style.display = 'none';
                })
                .finally(() => {
                    isConnecting = false;
                    connectBtn.disabled = false;
                    connectText.textContent = '连接WiFi';
                });
        }

        // 分析WiFi连接错误类型
        function analyzeWiFiError(errorMessage) {
            const message = errorMessage.toLowerCase();
            
            // 密码错误相关关键词 - 增加更多ESP32相关的错误信息
            if (message.includes('password') || message.includes('auth') || message.includes('authentication') ||
                message.includes('密码') || message.includes('认证') || message.includes('验证失败') ||
                message.includes('密码错误') || message.includes('密码不正确') || message.includes('401') ||
                message.includes('unauthorized') || message.includes('psk') ||
                message.includes('wifi密码错误') || message.includes('请重新输入') ||
                message.includes('handshake') || message.includes('4way_handshake') || message.includes('auth_fail')) {
                return {
                    type: 'password',
                    message: '❌ 密码错误：WiFi密码不正确，请检查后重新输入',
                    shortMessage: '密码错误',
                    canRetry: false,
                    suggestion: '请检查WiFi密码是否正确，注意区分大小写'
                };
            }
            
            // 网络不存在
            if (message.includes('not found') || message.includes('no ap') || message.includes('未找到') ||
                message.includes('网络不存在') || message.includes('网络名称') || message.includes('404')) {
                return {
                    type: 'network',
                    message: '📶 网络未找到：找不到指定的WiFi网络',
                    shortMessage: '网络未找到',
                    canRetry: true,
                    suggestion: '请确认WiFi名称正确，或刷新WiFi列表'
                };
            }
            
            // 信号弱或超时
            if (message.includes('timeout') || message.includes('weak') || message.includes('signal') ||
                message.includes('超时') || message.includes('信号') || message.includes('连接超时')) {
                return {
                    type: 'signal',
                    message: '📶 连接超时：WiFi信号可能较弱或距离过远',
                    shortMessage: '连接超时',
                    canRetry: true,
                    suggestion: '请靠近WiFi路由器或检查信号强度'
                };
            }
            
            // 网络繁忙
            if (message.includes('busy') || message.includes('full') || message.includes('繁忙') ||
                message.includes('连接数已满') || message.includes('too many')) {
                return {
                    type: 'busy',
                    message: '🚫 网络繁忙：WiFi连接数已满或网络繁忙',
                    shortMessage: '网络繁忙',
                    canRetry: true,
                    suggestion: '请稍后重试或联系网络管理员'
                };
            }
            
            // DHCP或IP分配失败
            if (message.includes('dhcp') || message.includes('ip') || message.includes('地址分配') ||
                message.includes('获取ip失败')) {
                return {
                    type: 'dhcp',
                    message: '🌐 IP分配失败：无法从路由器获取IP地址',
                    shortMessage: 'IP分配失败',
                    canRetry: true,
                    suggestion: '路由器DHCP可能有问题，请检查路由器设置'
                };
            }
            
            // 网络设置或信号问题
            if (message.includes('网络设置') || message.includes('信号强度')) {
                return {
                    type: 'network_settings',
                    message: '⚙️ 网络设置问题：WiFi连接失败',
                    shortMessage: '网络设置问题',
                    canRetry: true,
                    suggestion: '请检查WiFi路由器设置或信号强度'
                };
            }
            
            // 网络请求失败
            if (message.includes('network') || message.includes('fetch') || message.includes('请求失败')) {
                return {
                    type: 'network_error',
                    message: '🔌 网络请求失败：设备网络连接异常',
                    shortMessage: '网络异常',
                    canRetry: true,
                    suggestion: '请检查设备网络连接'
                };
            }
            
            // 默认未知错误
            return {
                type: 'unknown',
                message: '❓ 连接失败：' + errorMessage,
                shortMessage: '连接失败',
                canRetry: true,
                suggestion: '请检查WiFi设置或联系技术支持'
            };
        }

        // 显示错误操作建议
        function showErrorActions(errorInfo) {
            const statusDiv = document.getElementById('status');
            
            // 移除现有的操作按钮
            const existingActions = statusDiv.querySelectorAll('.error-action');
            existingActions.forEach(btn => btn.remove());
            
            const actionContainer = document.createElement('div');
            actionContainer.className = 'error-actions';
            actionContainer.style.marginTop = '15px';
            
            if (errorInfo.type === 'password') {
                // 密码错误 - 提供修改密码和显示密码的选项
                const changePasswordBtn = document.createElement('button');
                changePasswordBtn.textContent = '🔑 重新输入密码';
                changePasswordBtn.className = 'error-action';
                changePasswordBtn.style.background = 'linear-gradient(135deg, #e67e22, #d35400)';
                changePasswordBtn.style.marginRight = '10px';
                changePasswordBtn.onclick = () => {
                    const passwordInput = document.getElementById('password');
                    const passwordGroup = passwordInput.closest('.input-group');
                    
                    // 清除错误状态
                    passwordInput.classList.remove('password-error');
                    passwordGroup.classList.remove('password-input-error');
                    passwordInput.style.borderColor = '#3498db';
                    passwordInput.style.backgroundColor = 'white';
                    
                    // 清空密码并聚焦
                    passwordInput.value = '';
                    passwordInput.focus();
                    
                    // 移除错误提示
                    actionContainer.remove();
                    
                    showToast('请重新输入正确的WiFi密码', 'info');
                };
                
                const showPasswordBtn = document.createElement('button');
                showPasswordBtn.textContent = '👁️ 显示密码';
                showPasswordBtn.className = 'error-action';
                showPasswordBtn.style.background = 'linear-gradient(135deg, #9b59b6, #8e44ad)';
                showPasswordBtn.onclick = () => {
                    const passwordInput = document.getElementById('password');
                    const toggleBtn = document.getElementById('password-toggle');
                    if (passwordInput.type === 'password') {
                        passwordInput.type = 'text';
                        toggleBtn.textContent = '🙈';
                        showPasswordBtn.textContent = '🙈 隐藏密码';
                    } else {
                        passwordInput.type = 'password';
                        toggleBtn.textContent = '👁️';
                        showPasswordBtn.textContent = '👁️ 显示密码';
                    }
                };
                
                const retryWithNewPasswordBtn = document.createElement('button');
                retryWithNewPasswordBtn.textContent = '🔄 用新密码连接';
                retryWithNewPasswordBtn.className = 'error-action';
                retryWithNewPasswordBtn.style.background = 'linear-gradient(135deg, #28a745, #20c997)';
                retryWithNewPasswordBtn.onclick = () => {
                    const ssid = document.getElementById('ssid').value.trim();
                    const newPassword = document.getElementById('password').value;
                    
                    if (!newPassword) {
                        showToast('请先输入WiFi密码', 'error');
                        document.getElementById('password').focus();
                        return;
                    }
                    
                    // 重置重试计数
                    retryCount = 0;
                    actionContainer.remove();
                    
                    // 清除错误状态
                    const passwordInput = document.getElementById('password');
                    const passwordGroup = passwordInput.closest('.input-group');
                    passwordInput.classList.remove('password-error');
                    passwordGroup.classList.remove('password-input-error');
                    
                    // 开始新的连接尝试
                    setTimeout(() => connectWiFi(ssid, newPassword), 500);
                };
                
                actionContainer.appendChild(changePasswordBtn);
                actionContainer.appendChild(showPasswordBtn);
                actionContainer.appendChild(retryWithNewPasswordBtn);
                
            } else if (errorInfo.type === 'network') {
                // 网络不存在 - 提供刷新列表和手动输入选项
                const refreshBtn = document.createElement('button');
                refreshBtn.textContent = '🔄 刷新列表';
                refreshBtn.className = 'error-action';
                refreshBtn.style.background = 'linear-gradient(135deg, #28a745, #20c997)';
                refreshBtn.style.marginRight = '10px';
                refreshBtn.onclick = () => {
                    scanWiFi();
                    actionContainer.remove();
                };
                
                const manualBtn = document.createElement('button');
                manualBtn.textContent = '✏️ 手动输入';
                manualBtn.className = 'error-action';
                manualBtn.style.background = 'linear-gradient(135deg, #17a2b8, #138496)';
                manualBtn.onclick = () => {
                    const ssidInput = document.getElementById('ssid');
                    ssidInput.focus();
                    ssidInput.select();
                    actionContainer.remove();
                };
                
                actionContainer.appendChild(refreshBtn);
                actionContainer.appendChild(manualBtn);
                
            } else if (errorInfo.type === 'signal') {
                // 信号问题 - 提供信号检查建议
                const checkSignalBtn = document.createElement('button');
                checkSignalBtn.textContent = '📶 检查信号';
                checkSignalBtn.className = 'error-action';
                checkSignalBtn.style.background = 'linear-gradient(135deg, #fd7e14, #e8590c)';
                checkSignalBtn.onclick = () => {
                    showToast('建议：1. 靠近路由器 2. 检查路由器是否正常工作 3. 避免障碍物遮挡', 'info');
                    actionContainer.remove();
                };
                
                actionContainer.appendChild(checkSignalBtn);
            }
            
            // 添加建议文字
            if (errorInfo.suggestion) {
                const suggestionText = document.createElement('p');
                suggestionText.textContent = errorInfo.suggestion;
                suggestionText.style.fontSize = '12px';
                suggestionText.style.color = '#666';
                suggestionText.style.marginTop = '10px';
                suggestionText.style.marginBottom = '0';
                actionContainer.appendChild(suggestionText);
            }
            
            statusDiv.appendChild(actionContainer);
        }

        // 显示重试选项
        function showRetryOption(ssid, password, errorInfo, shouldRetry) {
            if (!shouldRetry || retryCount >= MAX_RETRY) return;
            
            const retryBtn = document.createElement('button');
            retryBtn.textContent = `🔄 重试连接 (${retryCount}/${MAX_RETRY})`;
            retryBtn.className = 'error-action';
            retryBtn.style.background = 'linear-gradient(135deg, #f39c12, #e67e22)';
            retryBtn.style.marginTop = '10px';
            retryBtn.onclick = () => {
                retryBtn.remove();
                // 重置密码输入框样式
                const passwordInput = document.getElementById('password');
                passwordInput.style.borderColor = '#e0e0e0';
                passwordInput.style.backgroundColor = '#fafafa';
                
                setTimeout(() => connectWiFi(ssid, password), 1000);
            };
            
            const statusDiv = document.getElementById('status');
            statusDiv.appendChild(retryBtn);
        }

        function showStatus(message, type) {
            const status = document.getElementById('status');
            status.textContent = message;
            status.className = 'status ' + type;
            status.style.display = 'block';
        }

        function clearConfig() {
            if (confirm('确定要清除WiFi配置吗？\n这将删除已保存的WiFi信息并重启设备。')) {
                showToast('正在清除WiFi配置...', 'info');
                
                fetch('/clear', { method: 'POST' })
                    .then(response => {
                        if (!response.ok) throw new Error('网络请求失败');
                        return response.json();
                    })
                    .then(data => {
                        if (data.success) {
                            showStatus('WiFi配置已清除，设备正在重启...', 'success');
                            showToast('WiFi配置已清除', 'success');
                            
                            // 清空表单
                            document.getElementById('ssid').value = '';
                            document.getElementById('password').value = '';
                            selectedSSID = '';
                            
                            // 清除选中状态
                            document.querySelectorAll('.wifi-item').forEach(item => 
                                item.classList.remove('selected')
                            );
                            
                        } else {
                            throw new Error(data.message || '清除失败');
                        }
                    })
                    .catch(error => {
                        showStatus('清除失败: ' + error.message, 'error');
                        showToast('清除失败: ' + error.message, 'error');
                    });
            }
        }

        // 键盘快捷键支持
        document.addEventListener('keydown', function(e) {
            // Ctrl+R / Cmd+R - 刷新WiFi列表
            if ((e.ctrlKey || e.metaKey) && e.key === 'r') {
                e.preventDefault();
            scanWiFi();
                return;
            }
            
            // Enter - 在SSID输入框时聚焦密码框，在密码框时连接
            if (e.key === 'Enter') {
                const activeElement = document.activeElement;
                if (activeElement.id === 'ssid') {
                    e.preventDefault();
                    document.getElementById('password').focus();
                } else if (activeElement.id === 'password') {
                    e.preventDefault();
                    document.getElementById('wifi-form').dispatchEvent(new Event('submit'));
                }
                return;
            }
            
            // Escape - 清除选择
            if (e.key === 'Escape') {
                document.querySelectorAll('.wifi-item').forEach(item => 
                    item.classList.remove('selected')
                );
                selectedSSID = '';
                document.getElementById('ssid').value = '';
                document.getElementById('password').value = '';
                showToast('已清除选择', 'info');
                return;
            }
        });

        // 处理密码错误的特殊逻辑
        function handlePasswordError() {
            const passwordInput = document.getElementById('password');
            const passwordGroup = passwordInput.closest('.input-group');
            
            // 添加错误样式类
            passwordInput.classList.add('password-error');
            passwordGroup.classList.add('password-input-error');
            
            // 聚焦并选中密码
            passwordInput.focus();
            passwordInput.select();
            
            // 显示更明显的错误提示
            showDetailedPasswordError();
            
            // 监听密码输入变化，清除错误状态
            const clearErrorOnInput = () => {
                passwordInput.classList.remove('password-error');
                passwordGroup.classList.remove('password-input-error');
                passwordInput.style.borderColor = '#e0e0e0';
                passwordInput.style.backgroundColor = '#fafafa';
                
                // 移除事件监听器
                passwordInput.removeEventListener('input', clearErrorOnInput);
            };
            
            passwordInput.addEventListener('input', clearErrorOnInput);
            
            // 5秒后自动清除错误样式
            setTimeout(() => {
                passwordInput.classList.remove('password-error');
                passwordGroup.classList.remove('password-input-error');
            }, 5000);
        }

        // 显示详细的密码错误提示
        function showDetailedPasswordError() {
            const statusDiv = document.getElementById('status');
            
            // 创建密码错误提示框
            const errorTip = document.createElement('div');
            errorTip.className = 'error-suggestion';
            errorTip.innerHTML = `
                <strong>✅ 热点仍开启，可继续配网！</strong><br/>
                <strong>密码错误常见原因：</strong><br/>
                • 密码输入有误，请仔细检查<br/>
                • 注意区分大小写字母<br/>
                • 检查数字和特殊字符<br/>
                • 确认是否包含空格<br/>
                💡 请重新输入正确的WiFi密码
            `;
            
            // 移除现有的提示
            const existingTip = statusDiv.querySelector('.error-suggestion');
            if (existingTip) {
                existingTip.remove();
            }
            
            statusDiv.appendChild(errorTip);
            
            // 5秒后自动移除提示
            setTimeout(() => {
                if (errorTip.parentNode) {
                    errorTip.remove();
                }
            }, 8000);
        }

        // 增强表单验证
        function validateForm() {
            const ssid = document.getElementById('ssid').value.trim();
            const password = document.getElementById('password').value;
            
            // 清除之前的错误样式
            const passwordInput = document.getElementById('password');
            const passwordGroup = passwordInput.closest('.input-group');
            passwordInput.classList.remove('password-error');
            passwordGroup.classList.remove('password-input-error');
            passwordInput.style.borderColor = '#e0e0e0';
            passwordInput.style.backgroundColor = '#fafafa';
            
            if (!ssid) {
                showToast('请选择或输入WiFi名称', 'error');
                document.getElementById('ssid').focus();
                return false;
            }
            
            if (ssid.length > 32) {
                showToast('WiFi名称过长（最大32字符）', 'error');
                return false;
            }
            
            if (password.length > 64) {
                showToast('WiFi密码过长（最大64字符）', 'error');
                return false;
            }
            
            return true;
        }


    </script>
</body>

</html>